package geo.google.mapping;

import com.magenta.maxoptra.gis.GeoException;
import com.magenta.maxoptra.gis.GeoStatusCode;

import geo.google.datamodel.GeoAltitude;
import geo.google.datamodel.GeoCoordinate;
import static com.magenta.maxoptra.gis.GeoStatusCode.*;

public class MappingUtils {
    private MappingUtils() {
    }

    /**
     * Convert a string representation of {@link GeoCoordinate} to an {@link GeoCoordinate} object.
     *
     * @param coord - this must be in the format of statusCode(optional), latitude, longitude, altitude
     * @return - null if <code>coord</code> is null.
     * @throws com.magenta.maxoptra.gis.GeoException
     *
     */
    public static GeoCoordinate stringToCoordinate(String coord) throws GeoException {
        if (coord == null) {
            return new GeoCoordinate();
        }
        String[] items = coord.split(",");
        if (items.length == 3) {
            GeoCoordinate ret = new GeoCoordinate(Double.parseDouble(items[0]),
                    Double.parseDouble(items[1]),
                    new GeoAltitude(Double.parseDouble(items[2])));
            return ret;
        } else if (items.length == 4) {
            int code = Integer.parseInt(items[0]);
            GeoStatusCode status = getStatusCode(code);
            if (status != GeoStatusCode.G_GEO_SUCCESS) {
                throw new GeoException("Error Status Code: " + status.getCodeName(), status);
            } else {
                return new GeoCoordinate(Double.parseDouble(items[3]),
                        Double.parseDouble(items[2]), new GeoAltitude());
            }
        } else {
            throw new GeoException("Standardizer received unknown value: " + coord);
        }
    }

    /**
     * Retrun the corresponding GGeoStatusCode based from the input code.
     */
    public static GeoStatusCode getStatusCode(int code) {
        switch (code) {
            case 200:
                return G_GEO_SUCCESS;
            case 400:
                return G_GEO_BAD_REQUEST;
            case 500:
                return G_GEO_SERVER_ERROR;
            case 601:
                return G_GEO_MISSING_QUERY;
            case 602:
                return G_GEO_UNKNOWN_ADDRESS;
            case 603:
                return G_GEO_UNAVAILABLE_ADDRESS;
            case 604:
                return G_GEO_UNKNOWN_DIRECTIONS;
            case 610:
                return G_GEO_BAD_KEY;
            case 620:
                return G_GEO_TOO_MANY_QUERIES;
            default:
                return G_GEO_UNKOWN_STATUS;
        }
    }

}